<template>
	<view class="container">
		<view class="title">
			<text>智能无人化水果贩卖系统</text>
		</view>
		<!-- 连接状态 -->
		<view class="status" :style="{color: sharedState.isConnected ? 'green' : 'red'}">
			<text>连接状态: {{ sharedState.isConnected ? '已连接' : '未连接' }}</text>
		</view>

		<!-- 数据展示区 -->
		<view class="data">
			<view class="temperature">
				<view class="data-item">
					<text>温度: {{ temperature.toFixed(2) }}°C</text>
					<image class="data-image" src="../../static/images/wendu.png"></image>
				</view>
			</view>
			<view class="humidity">
				<view class="data-item">
					<text>湿度: {{ humidity.toFixed(2) }}%</text>
					<image class="data-image" src="../../static/images/shidu.png"></image>
				</view>
			</view>
			<view class="weight">
				<view class="data-item">
					<text>重量: {{ weight }}kg</text>
					<image class="data-image" src="../../static/images/weight.png"></image>
				</view>
			</view>
			<view class="weight">
				<view class="data-item">
					<text>坏果率: {{ bf_rate }}%</text>
					<image class="data-image" src="../../static/images/fruit.png"></image>
				</view>
			</view>
			<view class="weight">
				<view class="data-item">
					<text>坏果率香蕉: {{ bf_rate_apple }}%</text>
					<image class="data-image" src="../../static/images/banana.png"></image>
				</view>
			</view>
			<view class="weight">
				<view class="data-item">
					<text>坏果率苹果: {{ bf_rate_banana }}%</text>
					<image class="data-image" src="../../static/images/apple.png"></image>
				</view>
			</view>
		</view>

		<button @click="connectMqtt" :disabled="isLoading">
			{{ isLoading ? '连接中...' : sharedState.isConnected ? '已连接' : '连接MQTT' }}
		</button>

		<!-- 控制指令区 -->
		<view class="control">
			<!-- 摄像头 -->
			<view class="camera">
				<view class="control-item">
					<image class="control-image" src="../../static/images/shexiangtou.png"></image>
					<view class="control-buttons">
						<button @click="goPage">跳转至监控画面</button>
					</view>
				</view>
			</view>
			<!-- 新增控制页面跳转按钮 -->
			<view class="control">
				<view class="control-item">
					<image class="control-image" src="../../static/images/control.png"></image>
					<button @click="goControlPage">跳转到控制中心</button>
				</view>
			</view>			
			<!-- 通风开关 -->
<!-- 			<view class="ventilation">
				<view class="control-item">
					<view class="switch-container">
						<image class="control-image" src="../../static/images/tongfeng.png"></image>
						<text>通风</text>
						<switch :checked="fan" @change="toggleFan" :disabled="!isConnected"></switch>
					</view>
				</view>
			</view> -->
			<!-- 紫外灯杀菌 -->
<!-- 			<view class="germicidal">
				<view class="control-item">
					<view class="switch-container">
						<image class="control-image" src="../../static/images/light.png"></image>
						<text>杀菌</text>
						<switch :checked="Ultraviolet" @change="toggleUltraviolet" :disabled="!isConnected"></switch>
					</view>
				</view>
			</view> -->
			<!-- 舵机控制 -->
<!-- 			<view class="servo">
				<view class="control-item">
					<view class="switch-container">
						<image class="control-image" src="../../static/images/Servos.png"></image>
						<text>舵机</text>
						<switch :checked="Servos" @change="toggleServos" :disabled="!isConnected"></switch>
					</view>
				</view>
			</view> -->
			<!-- 加湿器 -->
<!-- 			<view class="humidifier">
				<view class="control-item">
					<view class="switch-container">
						<image class="control-image" src="../../static/images/jiashiqi.png"></image>
						<text>加湿</text>
						<switch :checked="humidifier" @change="toggleHumidifier" :disabled="!isConnected"></switch>
					</view>
				</view>
			</view> -->
			<!-- 智能控制 -->
<!-- 			<view class="ai">
				<view class="control-item">
					<view class="switch-container">
						<image class="control-image" src="../../static/images/ai.png"></image>
						<text>智控</text>
						<switch :checked="ai" @change="toggleAI" :disabled="!isConnected"></switch>
					</view>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script>
	import mqtt from "mqtt";
	import {
		inject
	} from 'vue';

	export default {
		setup() {
			const sharedState = inject('sharedState');
			return {
				sharedState
			};
		},

		data() {
			return {
				isLoading: false,
//				isConnected: false,
				weight: 0,
				bf_rate: 0,
				bf_rate_apple: 0,
				bf_rate_banana: 0,
				// fan: false, // 初始化为布尔值
				// Ultraviolet: false,
				// Servos: false,
				// humidifier: false,
				// ai: false,
				temperature: 0,
				humidity: 0,
//				client: null,
				// options: {
				// 	clientId: "k1yxa0Zedsn.vedio2|securemode=2,signmethod=hmacsha256,timestamp=1744028106471|",
				// 	username: "vedio2&k1yxa0Zedsn",
				// 	password: "be9ae002088947591be481c4d1a83b471ce110aef467ea2f8ab4e1dca81438fc",
				// 	protocolVersion: 4,
				// 	clean: true,
				// 	reconnectPeriod: 1000,
				// 	connectTimeout: 30 * 1000,
				// 	qos: 0,
				// 	keepalive: 60
				// },
				// aliyunInfo: {
				// 	productKey: "k1yxa0Zedsn",
				// 	deviceName: "vedio2",
				// 	deviceSecret: "b54300d2bae4269cd9e07c4f0561fc48",
				// 	regionId: "cn-shanghai",
				// 	pubTopic: "/sys/k1yxa0Zedsn/vedio2/thing/event/property/post",
				// 	subTopic: "/sys/k1yxa0Zedsn/vedio2/thing/service/property/set",
				// }
			};
		},

		methods: {
			async connectMqtt() {
				//if (this.isLoading || this.isConnected) return;
				if (this.isLoading || this.sharedState.isConnected) return
				this.isLoading = true;
				try {
					const host =
						`wss://${this.sharedState.aliyunInfo.productKey}.iot-as-mqtt.${this.sharedState.aliyunInfo.regionId}.aliyuncs.com`;
					this.sharedState.client = mqtt.connect(host, this.sharedState.options);

					this.sharedState.client.on("connect", () => {
						this.sharedState.isConnected = true;
						this.isLoading = false;
						console.log("MQTT 连接成功");
						this.subscribeTopic();
						uni.showToast({
							title: '连接成功',
							icon: 'success'
						});
					});

					this.sharedState.client.on("message", (topic, payload) => {
						try {
							const data = JSON.parse(payload.toString());
							console.log("收到消息:", data);

							if (data?.items) {
								this.temperature = data.items.temp?.value ?? this.temperature;
								this.weight = data.items.weight?.value ?? this.weight;
								this.humidity = data.items.Humidity?.value ?? this.humidity;
								this.bf_rate = data.items.bf_rate?.value ?? this.bf_rate;
								this.bf_rate_apple = data.items.bf_rate_apple?.value ?? this.bf_rate_apple;
								this.bf_rate_banana = data.items.bf_rate_banana?.value ?? this.bf_rate_banana;


								// 同步设备状态
								this.sharedState.deviceStates.fan = data.items.fan?.value === 1;
								this.sharedState.deviceStates.Ultraviolet = data.items.Ultraviolet?.value === 1;
								this.sharedState.deviceStates.Servos = data.items.Servos?.value === 1;
								this.sharedState.deviceStates.humidifier = data.items.humidifier?.value === 1;
								this.sharedState.deviceStates.ai = data.items.ai?.value === 1;

								if (data.items.image?.value) {
									this.displayBase64Image(data.items.image.value);
								}
							}
						} catch (error) {
							console.error("消息解析失败:", error);
						}
					});

					this.sharedState.client.on("error", (error) => {
						console.error("MQTT 连接错误:", error);
						this.sharedState.isConnected = false;
						this.isLoading = false;
						uni.showToast({
							title: '连接失败',
							icon: 'none'
						});
					});

					this.sharedState.client.on("close", () => {
						console.log("MQTT 连接断开");
						this.sharedState.isConnected = false;
						this.isLoading = false;
					});

				} catch (error) {
					console.error("连接异常:", error);
					this.isLoading = false;
					uni.showToast({
						title: '连接异常',
						icon: 'none'
					});
				}
			},

			displayBase64Image(base64Data) {
				try {
					let imageBase64 = base64Data;
					if (!imageBase64.startsWith('data:image')) {
						imageBase64 = 'data:image/jpeg;base64,' + imageBase64;
					}
					this.sharedState.imageSrc = imageBase64;
				} catch (error) {
					console.error("图片处理失败:", error);
				}
			},

			subscribeTopic() {
				if (!this.sharedState.client || !this.sharedState.isConnected) return;

				this.sharedState.client.subscribe(this.sharedState.aliyunInfo.subTopic, (err) => {
					if (err) {
						console.error("订阅失败:", err);
						uni.showToast({
							title: '订阅失败',
							icon: 'none'
						});
					} else {
						console.log("订阅成功:", this.sharedState.aliyunInfo.subTopic);
					}
				});
			},

			sendControlCommand(device, value) {
				if (!this.sharedState.client || !this.sharedState.isConnected) {
					uni.showToast({
						title: '未连接MQTT',
						icon: 'none'
					});
					return;
				}

				try {

					// let type;
					// if (device === 'fan') {
					// 	type = 'type1';
					// } else if (device === 'Ultraviolet') {
					// 	type = 'type2';
					// } else if (device === 'Servos') {
					// 	type = 'type3';
					// } else if (device === 'humidifier') {
					// 	type = 'type4';
					// }

					const payload = {
						method: "thing.event.property.post",
						params: {
							[device]: value,

						}
					};
					this.sharedState.client.publish(this.sharedState.aliyunInfo.pubTopic, JSON.stringify(payload));
					console.log("发布消息:", device, value);
				} catch (error) {
					console.error("发送指令失败:", error);
					uni.showToast({
						title: '指令发送失败',
						icon: 'none'
					});
				}
			},
			
			toggleFan(checked) {
				this.fan = !this.fan;
				this.sendControlCommand('fan', this.fan ? 0x1001 : 0x1000);
				console.log("通风开关状态:", this.fan);
			},
			toggleUltraviolet(checked) {
				this.Ultraviolet = !this.Ultraviolet;
				this.sendControlCommand('Ultraviolet', this.Ultraviolet ? 0x1101 : 0x1100);
				console.log("紫外灯开关状态:", this.Ultraviolet);
			},
			toggleServos(checked) {
				this.Servos = !this.Servos;
				this.sendControlCommand('Servos', this.Servos ? 0x1201 : 0x1200);
				console.log("舵机开关状态:", this.Servos);
			},
			toggleHumidifier(checked) {
				this.humidifier = !this.humidifier;
				this.sendControlCommand('humidifier', this.humidifier ? 0x1301 : 0x1300);
				console.log("加湿器开关状态:", this.humidifier);
			},
			toggleAI(checked) {
				this.ai = !this.ai;
				this.sendControlCommand('ai', this.ai ? 0x1401 : 0x1400);
				console.log("智能控制开关状态:", this.ai);
			},
			goPage() {
				uni.navigateTo({
					url: '/pages/camera/camera'
				});
				this.sendControlCommand('image',0x15);
			},
			 goControlPage() {
			      uni.navigateTo({
			        url: '/pages/control/control'
			      })
			    }
		},

		onUnload() {
			if (this.sharedState.client) {
				this.sharedState.client.end();
			}
		}
	};
</script>

<style>
	.title {
		font-size: 20px;
		text-align: center;
		padding: 20px;
		font-weight: bold;
	}

	.container {
		padding: 20px;
		font-size: 18px;
	}

	.status {
		margin-bottom: 20px;
		font-weight: bold;
	}

	.data {
		margin-bottom: 20px;
		display: flex;
		flex-direction: column;
		gap: 10px;
		border: 3px solid #ddd;
		border-radius: 20px;
		background-color: ivory;
		padding: 10px;
	}

	.data-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 8px;
	}

	.data-item text {
		font-size: 18px;
	}

	.data-image {
		width: 24px;
		height: 24px;
	}

	.control {
		margin-top: 20px;
		display: flex;
		flex-direction: column;
		gap: 12px;
		border: 1px solid #ddd;
		border-radius: 20px;
		padding: 10px;
	}

	.control-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10px;
		padding: 10px;
		
	}

	.switch-container {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.control-image {
		width: 32px;
		height: 32px;
	}

	.camera {
		background-color: azure;
		border: 2px solid #ddd;
		border-radius: 20px;
		
	}
	.control .control{
		margin-top: 0;
		background-color: darkseagreen;
		border: 2px solid #ddd;
		border-radius: 20px;
	}
	.ventilation {
		background-color: aliceblue;
		border: 2px solid #ddd;
		border-radius: 20px;
	}

	.germicidal {
		background-color: thistle;
		border: 2px solid #ddd;
		border-radius: 20px;
	}

	.servo {
		background-color: lightgoldenrodyellow;
		border: 2px solid #ddd;
		border-radius: 20px;
	}

	.humidifier {
		background-color: lightcyan;
		border: 2px solid #ddd;
		border-radius: 20px;
	}

	.ai {
		background-color: lightyellow;
		border: 2px solid #ddd;
		border-radius: 20px;
	}

	button {
		margin: 0;
		padding: 8px 12px;
		border: 1px solid #ddd;
		border-radius: 20px;
		background-color: ghostwhite;
		font-size: 14px;
	}

	button:disabled {
		opacity: 0.6;
	}

	button:active {
		background-color: #e6e6e6;
	}
</style>